package com.biubiu.universaladapter.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.biubiu.universaladapter.help.safeClick
import com.biubiu.universaladapter.listener.OnModuleItemClickListener
import com.biubiu.universaladapter.listener.OnModuleItemLongClickListener

abstract class BaseViewHolder<T>(@LayoutRes layoutId: Int, container: ViewGroup): RecyclerView.ViewHolder(
    LayoutInflater.from(container.context).inflate(layoutId, container, false)
) {
    private var mOnModuleItemClickListener: OnModuleItemClickListener<T>? = null
    private var mOnModuleItemLongClickListener: OnModuleItemLongClickListener<T>? = null

    fun bindData(data: T?, dataPosition: Int, layoutPosition: Int, payloads: List<*>?) {
        itemView.setOnClickListener(null)
        itemView.setOnLongClickListener(null)

        if(data == null){
            return
        }

        mOnModuleItemClickListener?.let {
            itemView.safeClick { mOnModuleItemClickListener!!.onModuleItemClick(data, dataPosition, layoutPosition) }
        }

        mOnModuleItemLongClickListener?.let {
            itemView.setOnLongClickListener {  mOnModuleItemLongClickListener!!.onModuleItemLongClick(data, dataPosition, layoutPosition) }
        }

        if (payloads == null || payloads.isEmpty()) {
            onBindData(data, dataPosition, layoutPosition)
        } else {
            onBindData(data, dataPosition, layoutPosition, payloads)
        }
    }

    /**
     * Bind the data to the view
     */
    abstract fun onBindData(data: T, dataPosition: Int, adapterPosition: Int)
    open fun onBindData(data: T, dataPosition: Int, adapterPosition: Int, payloads: List<*>) {}
    open fun onViewDetachedFromWindow() {}
    open fun onViewAttachedToWindow() {}

    /**
     * Set the click listener for the item
     */
    fun setOnModuleItemClickListener(onModuleItemClickListener: OnModuleItemClickListener<T>?) {
        mOnModuleItemClickListener = onModuleItemClickListener
    }

    /**
     * Set the long click listener for the item
     */
    fun setOnModuleItemLongClickListener(onModuleItemLongClickListener: OnModuleItemLongClickListener<T>?) {
        mOnModuleItemLongClickListener = onModuleItemLongClickListener
    }
}